<template>
  <div>
    <el-dialog
      title="新建发送任务"
      :visible.sync="visible" 
      @close="dialogClose"
      width="90%">
      <div class="newsend-tip">{{newSendData.title}}</div>
      <el-form :inline="true" ref="newSendForm" :model="newSendForm" class="newsend-wrap">
        <!-- <h4>发送对象</h4>
        <el-form-item label="" class="block-line">
          <el-radio-group v-model="radio" @change="importCustomer">
            <el-radio class="radio" label="1">选择已有会员</el-radio>
            <el-radio class="radio" label="2">导入意向客户</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="发送对象">
          <el-select v-model="customerType" @change="groupList.list = [];newSendForm.buyerGroupId=null">
            <el-option :value="1" label="会员"></el-option>
            <el-option :value="2" label="意向客户"></el-option>
          </el-select>
          <el-select v-model="type" @change="groupList.list = [];newSendForm.buyerGroupId=null">
            <el-option label="所属群组" :value="null"></el-option>
            <el-option label="静态群组" :value="2"></el-option>
            <el-option label="动态群组" :value="1"></el-option>
          </el-select>
          <el-select v-model="newSendForm.buyerGroupId" filterable remote :remote-method="getCusGroupList" :loading="groupLoading" placeholder="请输入关键词" clearable>
            <el-option v-for="item,n in groupList.list" :value="item.id" :label="item.name" :key="n.toString()"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="" class="condition-wrap">
          <keep-alive>
            <g-filter :new-send.sync="newSendObj" ref="filters"></g-filter>
          </keep-alive>
        </el-form-item> -->

        <el-form-item label="定时发送时间：" class="newsend-time">
          <el-date-picker
            v-model="newSendForm.plan.sendTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="newsend-btn">
        <el-button type="primary" :loading="isSave" @click="handleSendNow">立即发送</el-button>
        <el-button type="primary" :loading="isSave" @click="handleSendAtTime">定时发送</el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <h3>发送记录：</h3>
        <el-table v-loading="tbLoading" element-loading-text="拼命加载中" :data="sendRecords" stripe class="send-record-table">
          <el-table-column label="发送时间" width="" prop="title" width="400">
            <template slot-scope="scope">
              {{dateFormat(scope.row.sendTime)}}
            </template>
          </el-table-column>
          </el-table-column>
          <el-table-column label="发送对象" width="300">
            <template slot-scope="scope">
              {{scope.row.toNumbers}}
              <!-- <el-button type='text' @click="dlSendRecord(scope.row.planId)">下载</el-button> -->
              <a :href="baseUrl+'/content/sendplan/detail/download?planId='+scope.row.planId" download class="btn-primary">下载</a>
            </template>
          </el-table-column>
          <el-table-column label="发送方式" width="200"  class-name="is-center">
            <template slot-scope='scope'>
              {{scope.row.sendType === 1 ? '立即发送' : '定时发送'}}
            </template>
          </el-table-column>
          <el-table-column label="发送状态" width=""  class-name="is-center">
            <template slot-scope='scope'>
              {{sendStatus(scope.row.sendStatus)}}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog
      title="导入意向客户"
      :visible.sync="importCustomerDialog"
      width="30%"
      @close="importCustomerDialog=false;newSendForm.radio='1'"
      >
      <el-upload
        class="upload-demo"
        ref="upload"
        action="https://jsonplaceholder.typicode.com/posts/"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <span slot="footer">
        <el-button type="primary" @click="submitUpload">上 传</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {mapState, mapActions} from 'vuex'
  import gFilter from '../cusManage/filter'
  import env from '@/config/env'
  export default {
    data () {
      return {
        customerType: 1,
        type: null,
        groupLoading: false,
        newSendForm: {
          plan: {
            type: this.newSendData.type,
            newsId: '',
            sendType: 1,
            sendTime: ''
          },
          buyerGroupId: '',
          type: 1,
          queryParam: {
            relationType: 1,
            conditionsGroup: []
          }
        },
        radio: '1',
        tbLoading: false,
        visible: this.show,
        newSendObj: {
          flag: false,
          id: '1'
        },
        importCustomerDialog: false,
        fileList: [],
        page: 1,
        size: 10,
        baseUrl: env.baseUrl,
        isSave: false
      }
    },
    props: ['show', 'newSendData'],
    watch: {
      show (val) {
        this.visible = val
      },
      visible (val) {
        this.$emit('update:show', val)
        // if (this.$refs.filters) {
        //   this.$refs.filters.clearFilter()
        // }
      }
    },
    components: {gFilter},
    computed: {
      ...mapState({
        sendRecords: state => state.contentManage.sendRecordList,
        groupList: state => state.cusManage.groupList
      })
    },
    mounted () {
      if (this.$refs.filters) {
        this.$refs.filters.clearFilter()
      }
    },
    methods: {
      ...mapActions(['getCusGroups', 'newSendPlan', 'sendRecord', 'sendRecordDownLoad']),
      getCusGroupList (wd) {
        if (wd) {
          this.getCusGroups({
            wd: wd,
            type: this.type,
            customerType: this.customerType,
            status: 1,
            size: 100,
            page: 1})
        }
      },
      getSendRecord (id) {
        this.sendRecord({id: id})
        this.groupList.list = []
        this.$store.state.cusManage.groupList.list = []
        this.newSendForm.buyerGroupId = ''
      },
      dlSendRecord (planId) {
        this.sendRecordDownLoad({planId: planId})
      },
      sendStatus (n) {
        let str = ''
        switch (n) {
          case 0: str = '待发送'; break
          case 1: str = '发送中'; break
          case 2: str = '发送完成'; break
          default: str = '已取消'
        }
        return str
      },
      dialogClose () {
        if (this.$refs.filters) {
          this.$refs.filters.clearFilter()
        }
      },
      // 日期格式化
      dateFormat (date) {
        return this.$date.format(new Date(date), 'YYYY-MM-DD HH:mm:ss')
      },
      importCustomer () {
        if (this.newSendForm.radio === '2') {
          this.importCustomerDialog = true
        } else {
          this.importCustomerDialog = false
        }
      },
      // 发送对象检查
      checkSendCondition () {
        // let conditionObj = this.$_.cloneDeep(this.$refs.filters.conditions).conditionsGroup[0].conditions
        // for (let i = 0; i < conditionObj.length; i++) {
        //   let item = conditionObj[i]
        //   if (!item.pid || !item.fieldName || !item.pattern || item.content === '' || item.content === null) {
        //     this.$message.warning('请完善发送对象信息')
        //     return false
        //   }
        // }
        this.newSendForm.type = this.customerType
        if (!this.newSendForm.buyerGroupId) {
          this.$message.warning('请选择发送对象')
          return false
        }
        return true
      },
      // 立即发送
      async handleSendNow () {
        if (!this.checkSendCondition()) {
          return false
        }
        this.newSendForm.plan.newsId = this.newSendData.id
        this.newSendForm.plan.sendType = 1
        this.newSendForm.plan.sendTime = this.$date.format(new Date(), 'YYYY-MM-DD HH:mm:ss')
        // this.newSendForm.queryParam.conditionsGroup = this.$_.cloneDeep(this.$refs.filters.conditions).conditionsGroup
        this.isSave = true
        await this.newSendPlan({...this.newSendForm}).then((res) => {
          this.isSave = false
          if (res.data.code === 1) {
            this.$message.success(res.data.msgZ)
            this.getSendRecord(this.newSendData.id)
          } else {
            this.$message.warning(res.data.msgZ)
          }
        })
      },
      // 定时发送
      async handleSendAtTime () {
        if (!this.checkSendCondition()) {
          return
        }
        if (!this.newSendForm.plan.sendTime) {
          this.$message({
            type: 'warning',
            message: '请选择发送时间'
          })
          return
        }
        this.newSendForm.plan.newsId = this.newSendData.id
        this.newSendForm.plan.sendType = 2
        this.newSendForm.plan.sendTime = this.dateFormat(this.newSendForm.plan.sendTime)
        // this.newSendForm.queryParam.conditionsGroup = this.$_.cloneDeep(this.$refs.filters.conditions).conditionsGroup
        this.isSave = true
        await this.newSendPlan({...this.newSendForm}).then((res) => {
          this.isSave = false
          if (res.data.code === 1) {
            this.$message.success(res.data.msgZ)
            this.getSendRecord(this.newSendData.id)
          } else {
            this.$message.warning(res.data.msgZ)
          }
        })
      },
      submitUpload () {
        this.$refs.upload.submit()
      },
      handleRemove (file, fileList) {
        console.log(file, fileList)
      },
      handlePreview (file) {
        console.log(file)
      }
    }
  }
</script>
<style lang="scss">
  .newsend{
    &-tip{
      background: #f3f3f3;
      padding: 10px 10px 30px;
      margin: -10px auto 15px;
    }
    &-time{
      // width: 100%;
    }
  }
  .condition-wrap{
    width: 100%;
    > div{
      width: 100%;
    }
  }
  .el-popover{
    word-wrap: break-word;
    word-break: break-all;
  }
  .newsend-btn{
    text-align: center;
  }
  .dialog-footer{
    text-align: left;
    padding: 15px 0 20px;;
    border-top: 1px dashed #dedede;
  }
  .send-record-table{
    margin-top: 10px;
  }
</style>
